Vue.component('yl-button', {
    template: `
    <span>
        <el-button :type="type" @click="Export" :loading="loading">
            <slot></slot>
        </el-button>
        <el-table id="ExportData" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" prop="Purchase_Order_SerialNumber" width="300" show-overflow-tooltip label="采购订单编号"></el-table-column>
        <el-table-column align="center" prop="Purchase_Date" width="300" show-overflow-tooltip label="提交时间"></el-table-column>
        <el-table-column align="center" prop="Supplier_SerialNumber" width="150" show-overflow-tooltip label="供应商主键"></el-table-column>
        <el-table-column align="center" prop="Supplier_Name" width="150" show-overflow-tooltip label="供应商"></el-table-column>
        <el-table-column align="center" prop="Amount" width="120" show-overflow-tooltip  label="金额"></el-table-column>
        <el-table-column align="center" prop="Purchase_Amount" width="120" show-overflow-tooltip  label="采购总价"></el-table-column>
        <el-table-column align="center" prop="Paid_Amount" width="120" show-overflow-tooltip label="已付金额"></el-table-column>
        <el-table-column align="center" label="开票状态">
            <template v-slot="{row}">
                <el-tag :type="row.Row_Status.charAt(1)=='0'?'':'success'">{{row.Row_Status.charAt(1)=='0'?'未开票':'已开票'}}</el-tag>
            </template>
        </el-table-column> 
        <el-table-column align="center"  width="100" label="付款状态">
            <template v-slot="{row}">
                <el-tag :type="row.Row_Status.charAt(0)=='0'?'':row.Row_Status.charAt(0)=='1'?'warning':'success'">{{Type(row.Row_Status)}}</el-tag>
            </template>
        </el-table-column> 
        </el-table>
    </span>`,
    props: ['loading', 'data', 'type'],
    computed: {
        Type() {
            return function (str) {
                switch (str.charAt(0)) {
                    case "0":
                        return "未付款";
                    case "1":
                        return "部分付款";
                    case "2":
                        return "已付款";
                    default:
                        return ""
                }
            }
        }
    },
    methods: {
        Export() {
            this.$emit('click')
        }
    }
})
Vue.component('yl-invoice', {
    template: `
    <span>
        <el-table id="ExportInvoice" :data="data" style="display: none; width: 100%;margin-bottom: 20px;">
        <el-table-column align="center" prop="Enterprise_Name" label="公司信息"></el-table-column>
        <el-table-column align="center" prop="Invoice_Type" label="发票类型"></el-table-column>
        <el-table-column align="center" prop="Invoice_Amount" label="开票金额"></el-table-column>
        <el-table-column align="center" prop="Article_Code" label="史泰博编码"></el-table-column>
        <el-table-column align="center" prop="Article_Name" label="产品详情"></el-table-column>
        <el-table-column align="center" prop="Sales_Unit_Price" label="单价"></el-table-column>
        <el-table-column align="center" prop="Quantity" label="数量"></el-table-column>
        <el-table-column align="center" prop="Reality_Amount" label="合计"></el-table-column>
        <el-table-column align="center" prop="Sales_Contacts" label="联系人"></el-table-column>
        <el-table-column align="center" prop="Sales_Phone" label="联系电话"></el-table-column>
        <el-table-column align="center" prop="Sales_Address" label="邮寄地址"></el-table-column>
        </el-table>
    </span>`,
    props: ['data'],
})
Vue.component('show-detail', {
    template: `<el-dialog title="详情查看" :visible.sync="visibleDialog" width="80vw">
    <el-tabs v-model="activeName">
        <el-tab-pane label="订单明细" name="1">
            <el-table :data="tableData" stripe border height="40vh" style="width: 100%">
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" width="200" show-overflow-tooltip prop="Sales_Order_Detail_SerialNumber" label="销售订单明细"></el-table-column>
                <el-table-column align="center" width="200" show-overflow-tooltip prop="Purchase_Order_SerialNumber" label="采购订单"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Supplier_Name" label="供应商"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Article_Name" label="商品名称"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Specifications_Name" label="规格名称"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Member_Name" label="下单账户"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Sales_Contacts" label="收件人"></el-table-column>
                <el-table-column align="center" width="120" show-overflow-tooltip prop="Sales_Phone" label="手机号"></el-table-column>
                <el-table-column align="center" width="170" show-overflow-tooltip prop="Sales_Date" label="下单时间"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Purchase_Unit_Price" label="采购单价"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Quantity" label="采购数量"></el-table-column>
                <el-table-column align="center" width="100" fixed="right" show-overflow-tooltip prop="Amount" label="采购总价"></el-table-column>
                <el-table-column align="center" prop="Row_Status" fixed="right" label="订单状态">
                    <template v-slot="{row}">
                        <el-tag :type="Type(row.Row_Status)[1]">
                            {{Type(row.Row_Status)[0]}}
                        </el-tag>
                    </template>  
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
                @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[20, 30, 50 ,100]"
                :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="付款详情" name="2">
            <el-table :data="tableData1" stripe border max-height="40vh" style="width: 100%">
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" prop="Payment_SerialNumber" label="付款单号"></el-table-column>
                <el-table-column align="center" width="180" show-overflow-tooltip prop="Payment_Date" label="付款时间"></el-table-column>
                <el-table-column align="center" prop="Supplier_Name" label="供应商"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Payment_Method" label="付款方式"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Amount" label="付款金额"></el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Payment_Voucher_Picture" label="付款凭证">
                    <template v-slot="{row}">
                        <el-image :preview-src-list="[row.Payment_Voucher_Picture]" v-if="row.Payment_Voucher_Picture" fit="contain" :src="row.Payment_Voucher_Picture" style="width:100px;height: 100px;"></el-image>
                        <span v-else>未上传凭证</span>
                    </template>  
                </el-table-column>
                <el-table-column align="center" show-overflow-tooltip prop="Row_Status" label="付款状态">
                    <template v-slot="{row}">
                        {{row.Row_Status!='0'?'已付款':'未付款'}}
                    </template>  
                </el-table-column>
                <el-table-column align="center" prop="Row_Status" label="对方是否确认">
                    <template v-slot="{row}">
                        {{row.Row_Status=='2'?'已确认':'未确认'}}
                    </template>  
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
            <el-button type="primary" @click="$emit('update:visible',false)">确定</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'visible'],
    data() {
        return {
            visibleDialog: false,
            tableData: [],//详情
            tableData1: [],//详情
            tableData2: [],
            form: {
                SQLSerialNumber: "P_business_purchase_order_detail",
                PaginationNumber: 1,//页数
                RowAmount: 10,//每页数据条数
                Condition: '',
                ExtensionCondition: '',
            },
            form1: {
                SQLSerialNumber: "P_business_payment_detail",
                Condition: '',
                ExtensionCondition: '',
            },
            total: 0,
            activeName: "1",
            loading: false,
        }
    },
    computed: {
        Type() {
            return function (str) {
                switch (str.charAt(1)) {
                    case "0":
                        return ["待付款", ""];
                    case "1":
                        return ["待付款", ""];
                    case "2":
                        return ["待付款", ""];
                    case "3":
                        return ["已付款", "success"];
                    case "4":
                        return ["已发货", "warning"];
                    case "5":
                        return ["已完成", "info"];
                    case "6":
                        return ["已取消", "danger"];
                    case "7":
                        return ["已取消", "danger"];
                    default:
                        return ""
                }
            }
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val);
            if (val) {
                this.tableData = [];
                this.tableData1 = [],//详情
                    this.tableData2 = [],
                    this.form.Condition = window.btoa(unescape(encodeURIComponent(this.data.Purchase_Order_SerialNumber)))
                this.form1.Condition = window.btoa(unescape(encodeURIComponent(this.data.Purchase_Order_SerialNumber)))
                this.getList(this.form);
                this.getList1(this.form1);
                this.getList2(this.data.Purchase_Order_SerialNumber)
            }
        },
    },
    methods: {
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        getList(data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    console.log(Result);
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList1(data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData1 = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList2(Purchase_Order_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: "business_purchase_order_invoice",
                    Condition: "Purchase_Order_SerialNumber='" + Purchase_Order_SerialNumber + "'"
                },
                success: function (Result) {
                    that.tableData2 = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQLSerialNumber: "P_business_purchase_order",
                PaginationNumber: 1,//页数
                RowAmount: 20,//每页数据条数
                Condition: '',
                ExtensionCondition: '',
                Supplier_SerialNumber: '',
                Purchase_Order_SerialNumber: '',
                Purchase_Date: null,
            },
            Supplier: [],
            total: 0,
            tableData: [],	//表格数据
            invoiceData: [],
            ExportData: [],//导出
            loading: false,
            dialogVisible: false,//详情
            dialogEditVisible: false,//付款
            dialogInvoiceVisible: false,//发票
            Purchase_Order: {},//当前选中的订单
        }
    },
    mounted() {
        if (getCookie('role')) {
            let roleObj = JSON.parse(getCookie('role'));
            this.form.Supplier_SerialNumber = roleObj.other
        }
        this.getList(this.form);//前端分页
    },
    computed: {
        Type() {
            return function (str) {
                switch (str.charAt(0)) {
                    case "0":
                        return "对方未付款";
                    case "1":
                        return "对方部分付款";
                    case "2":
                        return "对方已付款";
                    default:
                        return ""
                }
            }
        }
    },
    methods: {
        onSerach() {			//查询方法
            this.form.PaginationNumber = 1;
            this.getList(this.form)
        },
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        getList(form) {//换页方法
            const that = this
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Purchase_Order_SerialNumber + "%")))
            let sql = "";
            if (data.Purchase_Date) {
                sql = sql + "AND business_purchase_order.Purchase_Date BETWEEN '" + data.Purchase_Date[0] + "' AND '" + data.Purchase_Date[1] + "'\r\n"
            }
            if (data.Supplier_SerialNumber) {
                sql = sql + "AND business_purchase_order.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n"
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        Add() {
            window.location.href = './add.html'
        },
        Show(row) {//查看详情
            this.Purchase_Order = row;
            this.dialogVisible = true;
        },
        Edit(row) {
            this.Purchase_Order = row;
            this.dialogEditVisible = true;
        },
        Invoice(row) {
            const that = this;
            this.$prompt('请输入公司名称', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                this.loading = true;
                let data = {
                    SQLSerialNumber: "P_business_purchase_order_detail",
                    Condition: window.btoa(unescape(encodeURIComponent(row.Purchase_Order_SerialNumber))),
                    ExtensionCondition: ''
                }
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    type: 'POST',
                    data,
                    success: function (Result) {
                        console.log(Result);
                        let arr = [];
                        Result.forEach(item => {
                            arr.push({
                                Enterprise_Name: value,
                                Invoice_Type:'电子普票',
                                Invoice_Amount:row.Paid_Amount,
                                Article_Code:item.Article_Code,
                                Article_Name:item.Article_Name,
                                Sales_Unit_Price:item.Purchase_Unit_Price,
                                Quantity:item.Quantity,
                                Reality_Amount:item.Amount,
                                Sales_Contacts:item.Sales_Contacts,
                                Sales_Address:item.Sales_Address,
                                Sales_Phone:item.Sales_Phone
                            })
                        });
                        that.invoiceData = arr;
                        that.$nextTick(() => {
                            let wb = XLSX.utils.table_to_book(document.querySelector("#ExportInvoice"));
                            var wbout = XLSX.write(wb, {
                                bookType: "xlsx",
                                bookSST: true,
                                type: "array"
                            });
                            try {
                                saveAs(
                                    new Blob([wbout], {
                                        type: "application/octet-stream"
                                    }),
                                    "发票" + (+new Date()) + ".xlsx"
                                );
                            } catch (e) {
                                if (typeof console !== "undefined") console.log(e, wbout);
                            }
                            that.$message({
                                message: '已成功导出',
                                type: 'success'
                            })
                            return wbout;
                        })
                    },
                    complete: function (XMLHttpRequest) {
                        that.loading = false;
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                });
            }).catch(() => {});
            
        },
        Export(form) {//导出
            const that = this;
            this.loading = true;
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Purchase_Order_SerialNumber + "%")))
            let sql = "";
            if (data.Purchase_Date) {
                sql = sql + "AND business_purchase_order.Purchase_Date BETWEEN '" + data.Purchase_Date[0] + "' AND '" + data.Purchase_Date[1] + "'\r\n"
            }
            if (data.Supplier_SerialNumber) {
                sql = sql + "AND business_purchase_order.Supplier_SerialNumber = '" + data.Supplier_SerialNumber + "'\r\n"
            }
            data.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)));
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    if (Result.length > 0) {
                        that.ExportData = Result;
                        that.$nextTick(() => {
                            let wb = XLSX.utils.table_to_book(document.querySelector("#ExportData"));
                            var wbout = XLSX.write(wb, {
                                bookType: "xlsx",
                                bookSST: true,
                                type: "array"
                            });
                            try {
                                saveAs(
                                    new Blob([wbout], {
                                        type: "application/octet-stream"
                                    }),
                                    "采购订单表" + (+new Date()) + ".xlsx"
                                );
                            } catch (e) {
                                if (typeof console !== "undefined") console.log(e, wbout);
                            }
                            that.$message({
                                message: '已成功导出',
                                type: 'success'
                            })
                            return wbout;
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
    },
})